/* 
 * @(#)ClassLoaderUtil.java  1.0 2009-06-22
 * 
 * Copyright 2009 OSSoftware.  All rights reserved.
 */
package com.os.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

/**
 * Provides centralized classloader lookup.
 * 
 * @author David
 */
public class ClassLoaderUtil {
	/**
	 * LoadClass by class name
	 * 
	 * @param className
	 * @return
	 * @throws BPException
	 */
	public static Class loadClass(String className) throws BPException {
		try {
			return getClassLoader().loadClass(className);
		} catch (ClassNotFoundException e) {
			throw new BPException("class not found '" + className + "'", e);
		}
	}
    /**
     * Get the ClassLoader.
     *
     * @return ClassLoader
     */
	public static ClassLoader getClassLoader() {
		return ClassLoaderUtil.class.getClassLoader();
	}

	public static InputStream getStream(String resource) {
		return getClassLoader().getResourceAsStream(resource);
	}

	public static Properties getProperties(String resource) throws BPException {
		Properties properties = new Properties();
		try {
			properties.load(getStream(resource));
			
//			转码处理  
            Set<Object> keyset = properties.keySet();  
            Iterator<Object> iter = keyset.iterator();  
            while (iter.hasNext()) {  
                String key = (String) iter.next();  
                String newValue = null;  
                try {  
                    //属性配置文件自身的编码  
                    String propertiesFileEncode = "utf-8";  
                    newValue = new String(properties.getProperty(key).getBytes("ISO-8859-1"),propertiesFileEncode);  
                } catch (UnsupportedEncodingException e) {  
                    newValue = properties.getProperty(key);  
                }  
                properties.setProperty(key, newValue);  
            }  
		} catch (IOException e) {
			throw new BPException("couldn't load properties file '" + resource
					+ "'", e);
		}
		return properties;
	}

}
